import 'dart:collection';
import 'dart:convert' as convert;
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_web_study/api/dio_utils.dart';
import 'package:flutter_web_study/utils/toast_utils.dart';
import 'package:logger/logger.dart';

import '../api/app_config.dart';
import '../api/service_api.dart';
import '../bean/menu_item.dart';
import '../router/application.dart';
import '../router/routes.dart';
import 'dart:html' as html;

class ProductReviewViewModel extends ChangeNotifier {
  List imageList = [];
  TextEditingController controller = TextEditingController();
  BuildContext context;
  String jsonBean;
  int tagPage = 0;
  String goodsId = "";

  ProductReviewViewModel(this.context, this.tagPage, this.jsonBean);

  Map jsonMap = {};

  initView() {
    if (jsonBean != null) {
      jsonMap = jsonDecode(jsonBean) as Map;
    }
    // 0 评论  1编辑评论  2是种草秀 3是种草秀编辑
    switch (tagPage) {
      case 0:
        goodsId = jsonMap["goodsId"];
        break;
      case 1:
        goodsId = jsonMap["goodsId"];
        controller.text = jsonMap["content"];
        imageList = jsonMap["images"];
        break;
      case 2:
        break;
      case 3:
        break;
    }
    notifyListeners();
  }

  Future<void> addImage() async {
    html.FileUploadInputElement uploadInput = html.FileUploadInputElement();
    uploadInput.multiple = false; // 是否允许选择多文件
    uploadInput.draggable = true;
    uploadInput.click();
    uploadInput.onChange.listen((event) {
      // 选择完成
      html.File? file = uploadInput.files?.first;
      print('文件大小：${file?.size}');
      print('name:${file?.name}');
      if (file != null) {
        print('开始上传');
        html.FormData formData = html.FormData();
        formData.appendBlob('file', file.slice(), file.name);
        formData.append('folder', "comment");
        print('上传文件到服务器');
        // 上传文件到服务器
        var request = html.HttpRequest();
        request.open('POST', AppConfig.BASE_URL + ServiceApi.UPLOAD_FILE);
        request.send(formData);
        print('发送了');
        request.onLoadEnd.listen((event) {
          print('上传结果：${request.responseText}');
          if (request.responseText != null) {
            Map<String, dynamic> map = jsonDecode("${request.responseText}");
            if (map["code"] == 0) {
              String urlimage = map["data"];
              List split = urlimage.split(".");
              Map mapImage = {"type": 1, "image": urlimage};
              if (split.first == "mp4") {
                mapImage = {"type": 2, "image": urlimage};
              } else {
                mapImage = {"type": 1, "image": urlimage};
              }
              imageList.add(mapImage);
              notifyListeners();
            }
          }
        });
      }
    });
  }

  commentSure() {
    Map json = {
      "goodsId": goodsId,
      "content": controller.text.toString().trim(),
      "images": imageList,
      "commentId": "",
      "tags": []
    };

    DioUtils.getInstance()
        ?.post(ServiceApi.ADD_GOODS_COMMENT, {"json": jsonEncode(json)},
            (successCallBack) {
      ToastUtils.showToast(msg: "${successCallBack["message"]}");
      if (tagPage == 1) {
        jsonMap["content"] = controller.text.toString().trim();
        jsonMap["images"] = imageList;
      }
      Navigator.pop(context, jsonMap);
    }, (errorCallBack) {
      ToastUtils.showToast(msg: "${errorCallBack["message"]}");
    });
  }

  void deleteImageList(int index) {
    imageList.removeAt(index);
    notifyListeners();
  }
}
